package com.jzo2o.orders.manager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.foundations.ServeApi;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.utils.DateUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.orders.base.constants.RedisConstants;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.Client.CustomerClient;
import com.jzo2o.orders.manager.model.dto.request.PlaceOrderReqDTO;
import com.jzo2o.orders.manager.model.dto.response.PlaceOrderResDTO;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 下单服务类
 * </p>
 *
 * @author itcast
 * @since 2023-07-10
 */
@Slf4j
@Service
public class OrdersCreateServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersCreateService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CustomerClient customerClient;
    @Resource
    private ServeApi serveApi;

//  把这里的@Transactional注解去掉，因为这里面包括远程调用，时间太长
// ✅ 在方法中添加 @Transactional - 只包含数据库操作
////    @Transactional
//
    @Override
    public PlaceOrderResDTO placeOrder(PlaceOrderReqDTO placeOrderReqDTO) {
        //1、下单人信息获取
        AddressBookResDTO addressBook = customerClient
                .getDetail(placeOrderReqDTO.getAddressBookId());
        if(ObjectUtil.isEmpty(addressBook)){
            throw new CommonException("服务地址不能为空！");
        }

        ServeAggregationResDTO serveResDTO  = serveApi
                .findById(placeOrderReqDTO.getServeId());
        if(ObjectUtil.isEmpty(serveResDTO) ||
                ObjectUtil.notEqual(serveResDTO.getSaleStatus(),2)){
            throw new CommonException("服务不可用！");
        }

        //2、服务信息获取
        //2.1订单初始化数据
        Orders orders = new Orders();
        // id 订单id
        orders.setId(generateOrderId());
        // userId，从threadLocal获取当前登录用户的id，通过UserContextInteceptor拦截进行设置
        orders.setUserId(UserContext.currentUserId());
        // 服务id
        orders.setServeId(placeOrderReqDTO.getServeId());
        // 服务项id
        orders.setServeItemId(serveResDTO.getServeItemId());
        orders.setServeItemName(serveResDTO.getServeItemName());
        orders.setServeItemImg(serveResDTO.getServeItemImg());
        orders.setUnit(serveResDTO.getUnit());
        //服务类型信息
        orders.setServeTypeId(serveResDTO.getServeTypeId());
        orders.setServeTypeName(serveResDTO.getServeTypeName());
        // 订单状态
        orders.setOrdersStatus(0);
        // 支付状态，暂不支持，初始化一个空状态
        orders.setPayStatus(OrderPayStatusEnum.NO_PAY.getStatus());
        // 服务时间
        orders.setServeStartTime(placeOrderReqDTO.getServeStartTime());
        // 城市编码
        orders.setCityCode(serveResDTO.getCityCode());
        // 地理位置
        orders.setLon(addressBook.getLon());
        orders.setLat(addressBook.getLat());

        //省-市-区-地-址
        String serveAddress = new StringBuffer(addressBook.getProvince())
                .append(addressBook.getCity())
                .append(addressBook.getCounty())
                .append(addressBook.getAddress())
                .toString();
        orders.setServeAddress(serveAddress);
        // 联系人
        orders.setContactsName(addressBook.getName());
        orders.setContactsPhone(addressBook.getPhone());

        // 价格
        orders.setPrice(serveResDTO.getPrice());
        // 购买数量
        orders.setPurNum(NumberUtils.null2Default(placeOrderReqDTO.getPurNum(), 1));
        // 订单总金额 价格 * 购买数量
        orders.setTotalAmount(orders.getPrice().multiply(new BigDecimal(orders.getPurNum())));

        // 优惠金额 当前默认0
        orders.setDiscountAmount(BigDecimal.ZERO);
        // 实付金额 订单总金额 - 优惠金额
        orders.setRealPayAmount(NumberUtils.sub(orders.getTotalAmount(), orders.getDiscountAmount()));
        //排序字段,根据服务开始时间转为毫秒时间戳+订单后5位
        long sortBy = DateUtils.toEpochMilli(orders.getServeStartTime()) + orders.getId() % 100000;
        orders.setSortBy(sortBy);
        boolean save = this.save(orders);
        if(!save){
            throw new CommonException("添加订单失败！");
        }
        return new PlaceOrderResDTO(orders.getId());
    }




    private Long generateOrderId(){
        //1、获取自增ID值
        Long increment = redisTemplate.opsForValue().increment(
                RedisConstants.Lock.ORDERS_SHARD_KEY_ID_GENERATOR,
                1);

        //2、2位年+2位月+2位日+13位序号
        Long orderId = DateUtils.getFormatDate(LocalDateTime.now(),"yyMMdd") * 10000000000000L
                +increment;
        return orderId;
    }


}
